package com.kevis.zhunblog.admin.security.service;

import com.kevis.zhunblog.core.entities.RoleEntity;
import com.kevis.zhunblog.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 * 会进入此判断是否有这个角色权限
 */
@Component
public class ZhunAccessDecisionManager implements AccessDecisionManager {
    @Autowired
    private RoleService sysRoleService;

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        //这边获取了 SecurityMetadataSource 里获取到的 role集合
        if (null == authentication) {
            throw new AccessDeniedException("当前访问没有权限");
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();//获取当前登录人认证信息
        //查询当前登录用户的角色是不是被禁用了
        GrantedAuthority[] grantedAuthorities = authorities.toArray(new GrantedAuthority[0]);
        GrantedAuthority grantedAuthority = grantedAuthorities[0];
        String role = grantedAuthority.getAuthority();
        RoleEntity roleEntity = sysRoleService.getById(role.replace("ROLE_",""));
        if (roleEntity == null || roleEntity.getStatus() != 0) {
            throw new AccessDeniedException("当前访问没有权限");
        }

        for (ConfigAttribute configAttribute : configAttributes) {
            String needCode = configAttribute.getAttribute();//获取到 role的值
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needCode)) {//比较是否role一样，都没有说明没有权限
                    return;
                }
            }
        }
        throw new AccessDeniedException("当前访问没有权限");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
